package com.hnas.eCard.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.dao.PageBean;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.eCard.dao.AccECardDAO;
import com.hnas.eCard.domain.ECardStatus;
import com.hnas.eCard.domain.SearchECardStatus;
import com.hnas.eCard.orm.AccECard;

@Component("accECardDAO")
public class AccECardDAOImpl extends BaseDaoImpl<AccECard> implements AccECardDAO {

	private Logger log = LoggerFactory.getLogger(AccECardDAOImpl.class);
	
	private String baseSql = "select e.* from tbl_acc_e_card e LEFT JOIN tbl_accinfo a ON a.id=e.acc_id where a.valid='1' and e.is_deleted = 0 ";
	
	public AccECardDAOImpl() {
		super(AccECard.class);
	}

	@Override
	public List<AccECard> findByECardSql(AccECard vo) {
		String sql = baseSql;
		Map<Integer, Object> map = new HashMap<Integer, Object>();
		int index = 1;
		if(null != vo){
			if(StringUtil.isNotEmpty(vo.getId())){//主键id
				sql += " and e.id = ?";
				map.put(index++ , vo.getId());
			}
			if(StringUtil.isNotEmpty(vo.getAccId())){//账户id
				sql += " and e.acc_id = ?";
				map.put(index++ , vo.getAccId());
			}
			if(StringUtil.isNotEmpty(vo.getAccNo())){//卡账户
				sql += " and e.acc_no = ?";
				map.put(index++ , vo.getAccNo());
			}
			if(StringUtil.isNotEmpty(vo.getCardNo())){//卡号
				sql += " and e.card_no = ?";
				map.put(index++ , vo.getCardNo());
			}
			if(StringUtil.isNotEmpty(vo.getStatus())){//卡状态 1、正常 2、转增中 3、退卡中 4、已退卡
				sql += " and e.status = ?";
				map.put(index++ , vo.getStatus());
			}
			if(StringUtil.isNotEmpty(vo.getCardMark())){//卡标记 1、电子卡 2、实体卡
				sql += " and e.card_mark = ?";
				map.put(index++ , vo.getCardMark());
			}
			if(StringUtil.isNotEmpty(vo.getExpiryDate())){//卡有效期 格式 :yyyyMMdd
				sql += " and e.expiry_date >= ?";
				map.put(index++ , vo.getExpiryDate());
			}
		}
		Query query = this.entityManager.createNativeQuery(sql, AccECard.class);
		log.info("查询语句：【{}】",sql);
		if(map.size() > 0){
			for(Entry<Integer, Object> entry : map.entrySet()){
				query.setParameter(entry.getKey(), entry.getValue());
			}
		}
		List<AccECard> list = query.getResultList();
		return list;
	}

	/**
	 * 
	 */
	@Override
	public List<AccECard> findECardsByStatus(String accId, String searchStatus, Integer pageNo, Integer pageSize) throws Exception{
		DTOPagedList<AccECard> pageList = new DTOPagedList<AccECard>();
		PageBean<AccECard> page = new PageBean<AccECard>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		StringBuffer sb = new StringBuffer();
		List<Object> paras = new ArrayList<Object>();
		int j = 1;
		sb.append(" from AccECard t where  t.isDeleted = 0 ");
		if(StringUtil.isNotEmpty(accId)){
			sb.append(" and t.accId =  ?"+j++);
			paras.add(accId.trim());
		}
		if(StringUtil.isNotEmpty(searchStatus)){
			if(searchStatus.trim().equals(SearchECardStatus.USED)){//可使用:正常
				searchStatus = "'"+ECardStatus.NORMAL+"'";
			}else if(searchStatus.trim().equals(SearchECardStatus.BACK)){//退卡:退卡中，已退卡
				searchStatus = "'"+ECardStatus.BACK_CARDING+"','"+ECardStatus.BACK_CARD+"'";
			}
			sb.append(" and t.status in ("+ searchStatus + " )");
//			paras.add(searchStatus);
			sb.append(" order by t.updateTime desc ");
			
		}
		page.setQuery(sb.toString());
		page.setQueryCount("select count(t.id) "+sb);
		this.queryByPage(page, paras.toArray());
		pageList.setPageNo(page.getPageNo());
		pageList.setPageSize(page.getPageSize());
		pageList.setTotalCount(page.getTotalCount());
		return page.getList();
	}

	@Override
	public AccECard saveOrUpdate(AccECard dto) throws Exception {
		AccECard vo = null;
		if(null != dto){
			if(StringUtil.isNotEmpty(dto.getId())){
				 vo = this.find(dto.getId());
			}
			
			if(null == vo){
				vo = dto;
				vo.setCreateTime(DateUtil.dateTimeToString(new Date()));
				vo.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				vo.setIsDeleted(false);
				this.persist(vo);
			}else{
				BeanUtils.copyProperties(dto, vo,new String[]{"id", "createTime"});
				vo.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				this.merge(vo);
			}
		}
		return vo;
	}

	@Override
	public List<AccECard> searchECardSql(AccECard vo, boolean checkDelete) {
		String sql = "select * from tbl_acc_e_card e where 1 = 1 ";
		Map<Integer, Object> map = new HashMap<Integer, Object>();
		int index = 1;
		if(null != vo){
			if(StringUtil.isNotEmpty(vo.getId())){//主键id
				sql += " and e.id = ?";
				map.put(index++ , vo.getId());
			}
			if(StringUtil.isNotEmpty(vo.getAccId())){//账户id
				sql += " and e.acc_id = ?";
				map.put(index++ , vo.getAccId());
			}
			if(StringUtil.isNotEmpty(vo.getAccNo())){//卡账户
				sql += " and e.acc_no = ?";
				map.put(index++ , vo.getAccNo());
			}
			if(StringUtil.isNotEmpty(vo.getCardNo())){//卡号
				sql += " and e.card_no = ?";
				map.put(index++ , vo.getCardNo());
			}
			if(StringUtil.isNotEmpty(vo.getStatus())){//卡状态 1、正常 2、转增中 3、退卡中 4、已退卡
				sql += " and e.status = ?";
				map.put(index++ , vo.getStatus());
			}
			if(StringUtil.isNotEmpty(vo.getCardMark())){//卡标记 1、电子卡 2、实体卡
				sql += " and e.card_mark = ?";
				map.put(index++ , vo.getCardMark());
			}
			if(StringUtil.isNotEmpty(vo.getExpiryDate())){//卡有效期 格式 :yyyyMMdd
				sql += " and e.expiry_date <= ?";
				map.put(index++ , vo.getExpiryDate());
			}
			if(checkDelete) { // true: 带入条件   false : 不带入条件
				sql += " and e.is_deleted = ?";
				map.put(index++ , vo.getIsDeleted());
			}
		}
		Query query = this.entityManager.createNativeQuery(sql, AccECard.class);
		log.info("查询语句：【{}】",sql);
		if(map.size() > 0){
			for(Entry<Integer, Object> entry : map.entrySet()){
				query.setParameter(entry.getKey(), entry.getValue());
			}
		}
		List<AccECard> list = query.getResultList();
		return list;
	}

	@Override
	public int unbindECard(String accId, String cardNo) {
		String sql = "update tbl_acc_e_card set is_deleted=1 where acc_id = ?1 and card_no = ?2 and is_deleted=0";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, accId);
		query.setParameter(2, cardNo);
		return query.executeUpdate();
	}

}
